<template>
  <div class="search-container">
    <form action="/" class="search">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResult = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result 
    v-if="isResult"
    :searchText="searchText"
    ></search-result>
     <!-- 搜索建议/联想 -->
    <search-suggestion
    v-else-if="searchText" 
    :searchText="searchText"
    @search="onSearch"
    ></search-suggestion>
    <!-- 搜索历史 -->
    <search-history 
    v-else 
    :searchHistories="searchHistories"
    @search="onSearch"
    ></search-history>
    
    
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResult from './components/search-result.vue'
import { getItem, setItem} from '../../utils/storage'
export default {
  name: "SearchPage",
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  props: {},
  data() {
    return {
      searchText: '',
      isResult : false,  // 控制搜索结果的展示
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || [], // 搜索的历史记录数组
     
    };
  },
  computed: {},
  watch: {
    searchHistories(vaule) {
      setItem('TOUTIAO_SEARCH_HISTORIES', vaule)
    }
  },
  created() {},
  methods: {
     onSearch(val) {
       // 渲染搜索结果
      this.searchText = val
      // 更新文本框内容
      // this.searchHistory.push(val)
      // 存储搜索历史记录
      // 要求: 不要有重复历史记录, 最新的排在最前面
     const index = this.searchHistories.indexOf(val)
      if(index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
      this.isResult = true
    },
    onCancel() {
     this.$router.back()
    },
  },
};
</script>

<style scoped lang="less">
.search-container {
  .van-search__action {
    color: #fff;
  }
  .search{
     padding-top: 106px;
    .van-search {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 1;
    }
    .van-search__action {
        color: #fff;
    }
  }
}

</style>